package com.wang.ddp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.ddp.dto.LoginFormDTO;
import com.wang.ddp.dto.Result;
import com.wang.ddp.dto.UserDTO;
import com.wang.ddp.entity.User;
import com.wang.ddp.mapper.UserMapper;
import com.wang.ddp.service.IUserService;
import com.wang.ddp.utils.RegexUtils;
import com.wang.ddp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.wang.ddp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1、校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2、如果不合法返回错误信息
            return Result.fail("手机号格式错误！");
        }


        //3、合法就生成验证码    是cn.hutool.core.util的工具包的功能
        String code = RandomUtil.randomNumbers(6);
        //4、保存验证码到session
//        session.setAttribute(phone,code);
        //4、保存验证码到redis，并设置有效期为5分钟
        stringRedisTemplate.opsForValue().set("phone:"+phone,code,5l, TimeUnit.MINUTES);
        //5、发送验证码
//        SMSUtils.sendMessage("王同学博客","SMS_274970468",phone,code);
        log.info(code);
        //6、返回ok
        return Result.ok();
    }

    @Override
    public Result verifyLogin(LoginFormDTO loginForm,HttpSession session) {
        String phone = loginForm.getPhone();
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        String code = stringRedisTemplate.opsForValue().get("phone:"+phone);
        if (code != null && code.equals(loginForm.getCode())){
            //如果验证码匹配成功
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = this.getOne(userLambdaQueryWrapper);
            if (user == null){
                //如果用户不存在，就执行注册，自动将手机号的用户信息保存到数据库
                this.save(createUserWithPhone(phone));
            }
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            //将用户信息保存到redis中
            //随机生成token，作为登录令牌
            String token  = UUID.randomUUID().toString(true);
            //将User对象转为HashMap存储
            Map<String, Object> map = BeanUtil.beanToMap(userDTO,
                    new HashMap<>(),
                    CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fielName,fielValue)->fielValue.toString())
            );

            //存储
            stringRedisTemplate.opsForHash().putAll("login:token:"+token,map);
            //设置token有效期
            stringRedisTemplate.expire("login:token:"+token, 30L,TimeUnit.MINUTES);
            //登录成功后，删除redis中的验证码
            stringRedisTemplate.delete("phone:"+phone);
            //返回token
            return Result.ok(token);
        }else{
            //如果验证码匹配不成功
            return Result.fail("验证码错误！");
        }
    }

    @Override
    public Result sign() {
        //获取当前用户id
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("请先登录！");
        }
        Long userId = user.getId();
        //构造key，key = userId:年:月   value = 二进制
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + userId + now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //获取今天是这个月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //往redis存入数据    setbit key offset 1 因为redis下标是从0开始，所以今天是第几天，offset就是dayOfMonth - 1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取当前用户id
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("请先登录！");
        }
        Long userId = user.getId();
        //构造key，key = userId:年:月   value = 二进制
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + userId + now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //获取今天是这个月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取签到记录的二进制转为十进制的数值
        //bitfield sign:1010:2023:05 get u12 0
        List<Long> longs = stringRedisTemplate.opsForValue().bitField(
                key,        //key
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands        //bitfield有查询、修改、插入功能，这里使用查询功能get
                                .BitFieldType.unsigned(dayOfMonth)) //返回值无符号，表示u
                        .valueAt(0)     //从下标0开始获取
        );
        //因为bitfield可以同时进行查询、修改、插入操作，所以可能会有多个返回值，所以这里返回的是List集合
        if (longs == null || longs.isEmpty()){
            //没有签到记录
            return Result.ok(0);
        }
        Long sign = longs.get(0);
        if (sign == null || sign == 0){
            return Result.ok(0);
        }
        //一开始计数器为0
        int count = 0;
        //如果当天签到了，那么计数器加1，当天没签到也没关系，连续签到从昨天开始计算
        if ((sign & 1) == 1){
            count++;
        }
        sign >>>= 1;
        while(true){
            if ((sign & 1) == 0){
                break;
            }else {
                count ++;
            }
            //sign无符号右移一位
            sign >>>= 1;
        }
        return Result.ok(count);
    }

    /**
     * 创建用户
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+phone.substring(phone.length() - 6));
//        this.save(user);
        return user;
    }
}
